﻿function SocketHelper(params) {
   var options = $.extend({}, {
        uri: "ws://" + window.location.host + "/socket/connect",
        Received: function (result) { },//接收事件
        ReceiverId: "" //接收人
   }, params);
   var socket;//对象
   var SenderId = params.SenderId;//发送人
   var SenderName = params.SenderName;//发送人
    Connect = function () {
        // this.uri = uri;
        this.socket = new WebSocket(options.uri);
        this.socket.onopen = function (e) { _self.Open(e) };
        var _self = this;
        this.socket.onmessage = function (e) { _self.Received(e); };
        this.socket.onerror = function (e) { _self.Error(e); };
    };
    Send = function (ReceiverId, message) {
        var sendData = { "SenderId": SenderId, "SenderName": SenderName, "ReceiverId": ReceiverId, "MessageType": "text", "Content": message };
        try {
            this.socket.send(JSON.stringify(sendData));
        } catch (e) {
            this.Connect();

        }
        
    };
    Open = function (e) {
        this.Send("Service","连接");
        console.log("socket opened", e);
    };
    Close = function (e) {
        this.socket.close();
        console.log("socket closed", e);
    };
    Received = function (e) {
        var result = JSON.parse(e.data);
        if (options.Received) {
            options.Received(result);
        }
        if (result.SenderId == "Service" && result.Content == "open")
        {
            SenderId = result.ReceiverId;
            if (SenderName == "")
            {
                SenderName = SenderId;
            }
        }
       
        console.log("Received: " + result.ReceiverId);
    };
    Error = function (e) {
        console.log("Error: " + e.data);
    }
    return this;
}

